package ru.sharaf.selenium.applogic.implementation;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.ScreenshotException;
import org.testng.ITestResult;

import ru.sharaf.selenium.applogic.ApplicationManager;
import ru.sharaf.selenium.applogic.FilmHelper;
import ru.sharaf.selenium.applogic.NavigationHelper;
import ru.sharaf.selenium.applogic.UserHelper;
import ru.sharaf.selenium.model.User;
import ru.sharaf.selenium.util.Browser;
import ru.sharaf.selenium.util.PropertyLoader;
import ru.sharaf.selenium.webdriver.WebDriverFactory;

/**
 * Менеджер 
 */

public class AppManager implements ApplicationManager {

  private UserHelper userHelper;
  private FilmHelper filmHelper;
  private NavigationHelper navHelper;

  private WebDriver driver;
  private String baseUrl;
  private Browser browser;
  private String appUsername;
  private String appPassword;
  
  public AppManager() {
    baseUrl = PropertyLoader.loadProperty("site.url");
    String gridHubUrl = PropertyLoader.loadProperty("grid2.hub");

    browser = new Browser();
    browser.setName(PropertyLoader.loadProperty("browser.name"));
    browser.setVersion(PropertyLoader.loadProperty("browser.version"));
    browser.setPlatform(PropertyLoader.loadProperty("browser.platform"));

    String username = PropertyLoader.loadProperty("user.username");
    String password = PropertyLoader.loadProperty("user.password");
	
    appUsername = PropertyLoader.loadProperty("app.username");
	appPassword = PropertyLoader.loadProperty("app.password");
    
    driver = WebDriverFactory.getInstance(gridHubUrl, browser, username, password);

    userHelper = new UsrHelper(this);
    filmHelper = new MovieHelper(this);
    navHelper = new NavHelper(this);

    getNavigationHelper().gotoLoginPage();
  }

  protected WebDriver getWebDriver() {
    return driver;
  }

  protected String getBaseUrl() {
    return baseUrl;
  }
  
  /** Возвращает абсолютный путь к указанному файлу в папке,
	 *  объявленной как ресурс */
  protected String getFileAbsolutePath(String path){
		
	File f;
	f = new File(path);
	return f.getAbsolutePath().toString();
 }
	/** Именованные константы результатов теста */
 protected String getTestResult(ITestResult result) {
		
	String out = "N/A"; 
		
	switch  (result.getStatus()) {	
		case 1 : {
				out = "SUCCESS";
				break;
				}
		case 2 : {
				out = "FAILURE";
				break;
				}		
		case 3: {
				out = "SKIP";
				break;
				}	
		case 4: {	
				out = "SUCCESS_PERCENTAGE_FAILURE";
				break;	
				}		
		case 16: {	
				out = "STARTED";
				break;	
				}	
		}
	return out;
   } 

  /** Снятие скриншота */
 @Override 
 public void takeScreenshot(ITestResult result, String folder, String format) {

		Date date = new Date();
		String now = new SimpleDateFormat("ddMMYYHHMMss_").format(date);
		WebDriver returned;
			
		File screenshot = new File((getFileAbsolutePath(folder +"//"
								+ browser.getName()	+ "//" + now  
								+ "_" + result.getName()
								+ "_" + getTestResult(result) + format)));
		
		try {
				returned = new Augmenter().augment(driver); //grid
		} catch ( net.sf.cglib.core.CodeGenerationException ex) {
				returned = driver; //local
			}
			if (returned != null) { 
				try {
					File f = ((TakesScreenshot) returned)
							.getScreenshotAs(OutputType.FILE);
					FileUtils.copyFile(f, screenshot);
				} 
				catch (IOException e) {
						e.printStackTrace();
					}
				catch (ScreenshotException se) {
					   se.printStackTrace();
				  }
			}
	}  

  @Override
  public UserHelper getUserHelper() {
    return userHelper;
  }

  @Override
  public FilmHelper getFilmHelper() {
    return filmHelper;
  }

  @Override
  public NavigationHelper getNavigationHelper() {
    return navHelper;
  }
   
  @Override
  public void stop() {
    if (driver != null) {
      driver.quit();
    }
  }
  
  @Override
  public String getAppUsername(){
	   return appUsername;
  }
  
  @Override
  public String getAppPassword(){
	   return appPassword;
  }
  
  @Override 
  public void loginAsDefaultUser(){
	  User user = new User().setLogin(appUsername).setPassword(appPassword); 
	  getUserHelper().loginAs(user);
  }
  
}
